﻿using System;
using XCI.Core;
using XCI.Extensions;
using XCI.Helper;

namespace XCI.Windows
{
    public partial class FrmAppConfig : BaseForm
    {
        private AppHandler handler = new AppHandler();
        private AppSetting appSetting;
        public FrmAppConfig()
        {
            InitializeComponent();
        }

        private void Form_Load(object sender, EventArgs e)
        {
            appSetting = handler.LoadAppSetting();
            bindingSource.DataSource = appSetting;
            webApiClientConfigServerUserControl.Config = appSetting.Server;
            webApiClientConfigFileServerUserControl.Config = appSetting.FileServer;
            editEnableFileServer.Checked = appSetting.FileServer != null && appSetting.FileServer.BaseUrl.IsNotEmpty();
        }

        private void BtnSave_Click(object sender, EventArgs e)
        {
            appSetting.Server = webApiClientConfigServerUserControl.Config;
            appSetting.FileServer = webApiClientConfigFileServerUserControl.Config.BaseUrl.IsNotEmpty() ? webApiClientConfigFileServerUserControl.Config : null;
            if (appSetting.Server.BaseUrl.IsEmpty())
            {
                MessageBoxHelper.ShowWarn("请指定服务器基地址");
                return;
            }

            handler.SaveAppSetting();
            App.Setting = handler.LoadAppSetting();
            MessageBoxHelper.ShowMessage("保存成功");
        }

        private void btnTheme_Click(object sender, EventArgs e)
        {
            var frm = new FrmSettingThemeForm();
            frm.ShowDialog();
            frm.Dispose();
        }

        private void BtnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void EditEnableFileServer_CheckedChanged(object sender, EventArgs e)
        {
            layoutFileServerGroup.Visibility = WinFormHelper.LayoutItemVisible(editEnableFileServer.Checked);
            if (editEnableFileServer.Checked == false)
            {
                webApiClientConfigFileServerUserControl.Config.BaseUrl = string.Empty;
            }
        }
    }
}